/* 
// 如下方式 callback 会被执行两次, 所以自定义useMounted来实现组件挂载后执行指定回调
useEffect(() => {
    callback();
}, []);
*/

import { useEffect, useRef, useState } from "react";

export default function useMounted(callback: Fn, unmountedCallback?: Fn) {
  const callbackRef = useRef(callback);
  const isMountedRef = useRef(false);
  const countRef = useRef(0);

  useEffect(() => {
    countRef.current += 1;
    // console.log("===========  mounted...");
    if (isMountedRef.current) return;
    isMountedRef.current = true;
    callbackRef.current();

    return () => {
      // if call mounted twice in a short time, should not clear effect
      setTimeout(() => {
        if (countRef.current > 1) {
          return;
        }
        unmountedCallback?.();
      }, 200);
    };
  }, []);
}
